<template>
	<div class="chat1">

		<div v-if="report==0" style="width: 100%;position: fixed; z-index: 999; height: 100%; top: 0; left: 0;" @click="quanxian()"></div>

		<div :class="['TUI-chat', !isPC && 'TUI-chat-h5']">
			<div v-if="!currentConversationID" :class="['TUI-chat-default', !isPC && 'TUI-chat-h5-default']">
				<slot></slot>
			</div>
			<div v-if="currentConversationID" :class="['TUI-chat', !isPC && 'TUI-chat-h5']">
				<!-- :class="['TUI-chat-header', !isPC && 'TUI-chat-H5-header', isUniFrameWork && 'TUI-chat-uniapp-header']" -->
				<ChatHeader :class="['TUI-chat-header', !isPC && 'TUI-chat-H5-header']" @closeChat="closeChat">
				</ChatHeader>
				<Forward></Forward>
				<MessageList ref="MessageListRef" :class="['TUI-chat-message-list', !isPC && 'TUI-chat-h5-message-list']" :isGroup="isGroup" :groupID="groupID"
					@handleEditor="handleEditor" :style="`paddingBottom: ${paddingBottom}px`">
				</MessageList>
				<!-- 兼容 uni 打包支付宝小程序 v-show 无效问题 -->
				<MessageInputToolbar v-if="isToolbarShow" :class="['TUI-chat-message-input-toolbar', !isPC && 'TUI-chat-h5-message-input-toolbar']" @insertEmoji="insertEmoji">
				</MessageInputToolbar>
				<MessageInput v-if="!isExit"
					:class="['TUI-chat-message-input', !isPC && 'TUI-chat-h5-message-input', isUniFrameWork && 'TUI-chat-uni-message-input', isWeChat && 'TUI-chat-wx-message-input']"
					ref="messageInputRef" :isMuted="false" :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')" :placeholder="TUITranslateService.t(ru_input)"
					@handleToolbarListShow="handleToolbarListShow" @paddingKeyboard="paddingKeyboard">
				</MessageInput>
			</div>
			<!-- 群组管理 -->
			<div class="group-profile" v-if="isUniFrameWork && isGroup && groupManageExt && !isExit" @click="handleGroup">
				{{ groupManageExt.text }}
				<!-- 更多 -->
			</div>
		</div>
		<!-- <image class="header_bg" src="@/static/chat/header_bg.png" mode="widthFix"></image> -->
	</div>
</template>
<script lang="ts" setup>
	import TUIChatEngine, {
		TUITranslateService,
		TUIConversationService,
		TUIStore,
		StoreName,
		IMessageModel,
		IConversationModel,
		TUIGroupService,
	} from "@tencentcloud/chat-uikit-engine";
	import TUICore, { TUIConstants, ExtensionInfo } from "@tencentcloud/tui-core";
	import { ref, onUnmounted, onMounted } from "../../adapter-vue";
	import ChatHeader from "./chat-header/index.vue";
	import MessageList from "./message-list/index.vue";
	import MessageInput from "./message-input/index.vue";
	import Forward from "./forward/index.vue";
	import MessageInputToolbar from "./message-input-toolbar/index.vue";
	import { isPC, isWeChat, isUniFrameWork } from "../../utils/env";
	import TUIChatConfig from "./config";
	import {
		HTTP_REQUEST_URL,
		PERFIX,
		kfs,
		IM_SDKAppID
	} from '@/config/app';

	import { sendMessages } from "./utils/sendMessage";

	const TYPES = ref(TUIChatEngine.TYPES);

	const emits = defineEmits(["closeChat", "sendMessage"]);
	const isToolbarShow = ref<boolean>(!isUniFrameWork);
	const messageInputRef = ref();
	const currentConversationID = ref();
	// 是否显示群组管理
	const isGroup = ref(false);
	const groupID = ref("");
	const groupManageExt = ref<ExtensionInfo>(undefined);

	const isIs = ref(false);
	const currentConversation = ref<IConversationModel>(undefined);

	const paddingBottom = ref<string | number>(0);
	const MessageListRef = ref();

	const paddingKeyboard = (val : string | number) => {
		paddingBottom.value = val;
		handleToolbarListShow(false)
		MessageListRef?.value.scrollToBottom();
	}

	let ru_input = ref('TUIChat.请输入消息');
	if (getApp().globalData.lang === 'ru') {
		ru_input = ref('Введите сообщение');
	}

	let report = ref(0);
	if (getApp().globalData.chat_report2 == true) {
		report.value = 1;
	}


	const isAgree = async () => {
		// await sendMessages(
		// 	[
		// 		{
		// 			type: "is_agree",
		// 			payload: {
		// 				text: "ceshiceshi"
		// 			},
		// 		},
		// 	],
		// 	currentConversation.value
		// );
		// console.log("currentConversation.value====", currentConversation.value)
		// emits("sendMessage");
	}

	uni.request({
		url: HTTP_REQUEST_URL + '/common/getSite',
		success: (r) => {
			if (!isIs.value) {
				isIs.value = true;
				isAgree();
			}
			getApp().globalData.chat_report2 = r.data.data.chat_report2
			if (getApp().globalData.chat_report2 == true) {
				report.value = 1;
			}
		},
	})

	TUIStore.watch(StoreName.CONV, {
		currentConversation: (conversation : IConversationModel) => {
			if (currentConversationID.value === conversation?.conversationID) {
				return;
			}
			currentConversation.value = conversation;
			// TUIChat 每次切换会话，需要初始化 chatType;
			TUIChatConfig.setChatType(conversation?.type);
			// 由 TUICustomerServicePlugin 插件判断如果当前会话是客服会话，则设置 chatType 并激活会话。
			TUICore.callService({
				serviceName: TUIConstants.TUICustomerServicePlugin.SERVICE.NAME,
				method: TUIConstants.TUICustomerServicePlugin.SERVICE.METHOD.ACTIVE_CONVERSATION,
				params: { conversationID: conversation?.conversationID },
			});
			currentConversationID.value = conversation?.conversationID;
			isGroup.value = conversation?.type === TUIChatEngine.TYPES.CONV_GROUP;
			if (isUniFrameWork && isGroup.value && groupID.value !== conversation?.groupProfile?.groupID) {
				const extList = TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID, {
					filterManageGroup: !isGroup.value,
				});
				groupManageExt.value = extList[0];
			}
			if (isUniFrameWork && !isGroup.value) {
				groupManageExt.value = [];
			}
			groupID.value = conversation?.groupProfile?.groupID;
		},
	});

	let isExit = ref<boolean>(true);
	onMounted(async () => {
		let useId = PERFIX + uni.getStorageSync('mobile');
		if (!groupID.value) {
			isExit.value = false;
			return;
		}
		try {
			let res = await TUIGroupService?.getGroupMemberProfile({
				groupID: groupID.value,
				userIDList: [useId]
			})
			isExit.value = false;
		} catch (e) {
			isExit.value = true;
		}

	})

	onUnmounted(() => {
		reset();
	});


	// 清空当前 conversationID
	const reset = () => {
		TUIConversationService.switchConversation();
	};

	const closeChat = (conversationID : string) => {
		emits("closeChat", conversationID);
		reset();
	};

	const insertEmoji = (emojiObj : object) => {
		messageInputRef?.value?.insertEmoji(emojiObj);
	};

	const handleToolbarListShow = (show ?: boolean) => {
		if (isUniFrameWork) {
			isToolbarShow.value = (show === undefined) ? !isToolbarShow.value : show;
		} else {
			isToolbarShow.value = true;
		}
	};

	// const handleToolbarListShow = (show ?: boolean) => {
	// 	if (isUniFrameWork) {
	// 		isToolbarShow.value = !!show;
	// 	} else {
	// 		isToolbarShow.value = true;
	// 	}
	// };

	const quanxian = () => {
		let lang = getApp().globalData.lang;

		if (getApp().globalData.chat_report2 == false) {
			if (lang == 'ru') {
				uni.showModal({
					title: "ым при использовании приложения",
					content: "Доступ к фото и видео материалам" + "\n" +
						"Доступ к камере" + "\n" +
						"Доступ к файлам" + "\n" +
						"Разрешить доступ к микрофону:  для отправки голосовых сообщений в приложение.",
					confirmText: "Да",
					cancelText: "Нет",
					success(e) {
						if (e.confirm) {
							getApp().globalData.chat_report2 = true
							report.value = 1
						}
					}
				})
			} else {
				uni.showModal({
					title: "该功能将获取以下权限",
					content: "读取相册权限：以便您能够选择并上传图片或视频到我们的应用中" + "\n" +
						"摄像头权限：以便您能够选择并上传图片或视频到我们的应用中" + "\n" +
						"文件权限：以便您能够选择并上传文件到我们的应用中" + "\n" +
						"麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中",
					confirmText: "同意",
					cancelText: "算了",
					success(e) {
						if (e.confirm) {
							getApp().globalData.chat_report2 = true
							report.value = 1
						}
					}
				})
			}
			return
		} else {
			report.value = 1
		}
	}


	const handleEditor = (message : IMessageModel, type : string) => {
		if (!message || !type) return;
		switch (type) {
			case "reference":
				// todo
				break;
			case "reply":
				// todo
				break;
			case "reedit":
				if (message?.payload?.text) {
					messageInputRef?.value?.reEdit(message?.payload?.text);
				}
				break;
			default:
				break;
		}
	};

	const handleGroup = () => {
		groupManageExt.value.listener.onClicked({ groupID: groupID.value });
	};
</script>
<style scoped lang="scss" src="./style/index.scss"></style>
<style scoped lang="less">
	.chat1 {
		background: url("/static/chat/header_bg.png") no-repeat;
		background-position: top left;
		background-size: contain;
	}

	.header_bg {
		position: fixed !important;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 3;
	}

	// .TUI-chat-h5-message-list {
	// 	background: #fff;
	// 	border-radius: 48rpx 48rpx 0 0;
	// 	margin-top: 30rpx;
	// }
	.TUI-chat-message-list {
		background: #fff;
		border-radius: 48rpx 48rpx 0 0;
	}
</style>